package com.atguigu.listener;


import com.atguigu.utils.JDBCTools;
import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;

public class ContextListener implements ServletContextListener {


    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 注销JDBC驱动程序
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            java.sql.Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
                System.out.println("Deregistering JDBC driver: " + driver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 关闭Druid数据源
        if (JDBCTools.getDataSource() != null) {
            try {
                ((com.alibaba.druid.pool.DruidDataSource) JDBCTools.getDataSource()).close();
                System.out.println("Druid data source closed");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 停止 AbandonedConnectionCleanupThread
        try {
            AbandonedConnectionCleanupThread.uncheckedShutdown();
            System.out.println("AbandonedConnectionCleanupThread stopped");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
